<?php
/**
 * This file contains the base controller of all web interface monitor controllers.
 *
 * @author Vincent.Hou <vincenthou@augmentum.com.cn>
 */

/**
 * MonitorBaseController class is the base controllers of the moudule.
 *
 * @package system\resque\controllers
 * @author Vincent.Hou <vincenthou@augmentum.com.cn>
 *
 */
class ResqueBaseController extends CController
{

   public $layout = false;
   /**
    * Registers css and js file
    *
    * Registers css file when $fileName end by 'css' and registers script file when $fileName end by '.js'
    * Precondition: the css file at themeUrl/css and the script file at themeUrl/script
    *
    * @example
    *        Register css file or js file in action and render to pages.  <br>
    *          <code>
    *             $this->registerCssAndScript(array('site.css', 'site.js'))
    *          </code> <br>
    *
    *
    * @param array $fileName File names array
    */
    public function registerCssAndScript($fileName)
    {
        if(!empty($fileName))
        {
            $asssetsUrl = $this->module->assetsUrl;
            $cs = Yii::app()->getClientScript();
            $fileName = (array)$fileName;
            foreach($fileName as $name)
            {
                if('.css' == substr($name, -4, 4))
                {
                    $cs->registerCssFile($asssetsUrl . '/css/' . $name);
                }
                else if('.js' == substr($name, -3, 3))
                {
                    $cs->registerScriptFile($asssetsUrl . '/script/' . $name);
                }
            }
        }
    }

    /**
     * Load needed CSS and JS file for rendering the pages
     */
    protected function loadResource()
    {
        $this->registerCssAndScript(array('main.css'));
    }

    /**
     * Generate the request token for security
     * @param  object $curRedis The redis instance
     */
    protected function generateRequestToken($curRedis = null)
    {
        $token = uniqid();
        !isset($curRedis) && ($curRedis = Yii::app()->resque->redis());
        $curRedis->set('request:token:' . $token, time());
        $curRedis->expire('request:token:' . $token, Constant::$TOKEN_EXPIRE_TIME);
        return $token;
    }

    /**
     * Check if the resquest token is valid
     * @param  string $token Resquest token
     */
    protected function resquestTokenValid($token)
    {
        $isValid = false;
        if (!empty($token))
        {
            $isValid = (boolean) Yii::app()->resque->redis()->exists('request:token:' . $token);
        }
        return $isValid;
    }
}